import React, { useCallback, useEffect, useState } from 'react';
import { Row, Col, message } from 'antd';
import { DetailInfoPosDrawer, OrganizationTree, PositionTable, ConfirmModal } from './components/manage';
import { PositionContext, usePositionData } from './hooks';

import { positionAPI } from './type';

import cls from 'classnames';
import './styles.less';
import { connect, useRequest } from 'umi';
import { UpdatePosModal } from './components/update';
import { getPosColumns } from './components/manage/PageConfig';
import { rouleDutySubjectRequest } from './hooks/usePositionOperation';
import { getCompanyID, getPosIDs, getUserDepID, getUserID } from '@/utils';

const Index: React.FC<positionAPI.IPostionProps> = ({ permissions }) => {
  const prefix = 'position-row';

  const { orgTreeData, treeLoading, selectedKeys, tableLoading, dataSource, onTreeSelectChange, getTreeData, onTableReload } = usePositionData(permissions);

  const [showUpdateDrawer, setShowDrawer] = useState<boolean>(false); //新增打开modal
  const [deptCheckRows, setDeptCheckRows] = useState<any>(); //保存左侧点击的数据
  const setDeptTreeNode = useCallback(
    (rowObj: any) => {
      setDeptCheckRows(rowObj);
    },
    [deptCheckRows],
  );

  useEffect(() => {
    let columns = getPosColumns(permissions, onPosOptClick);
    changeColumns(columns);
  }, [deptCheckRows?.id, deptCheckRows?.isOpen]);

  // 是否打开禁用提示modal
  const [openConfirm, setOpenConfirm] = useState<boolean>(false);
  const [tableRowObj, setTableRowObj] = useState<any>(null);
  const onConfirmModal = useCallback(
    (record: Record<any, any>) => {
      setTableRowObj(record);
      setOpenConfirm(true);
    },
    [openConfirm],
  );
  const closeConfirmModal = useCallback(() => {
    setOpenConfirm(false);
  }, [openConfirm]);

  const onCloseUpdate = useCallback(() => {
    setShowDrawer(false);
  }, [showUpdateDrawer]);
  // 打开modal
  const onOpenUpdate = (cliRows: any, getIntoType: string) => {
    setShowDrawer(true);
    intoTypeCal(cliRows, getIntoType); //保存如何进入的modal
  };

  // 点击查看详情
  const [isShowDetail, setIsShowDetail] = useState<boolean>(false);
  const [resObj, setResObj] = useState<string>('');
  const onDetail = useCallback(
    (record: any) => {
      setIsShowDetail(true);
      setResObj(record);
    },
    [isShowDetail],
  );
  const closeDetail = useCallback(() => {
    setIsShowDetail(false);
  }, [isShowDetail]);

  const [intoModalType, setIntoModalType] = useState<string>(''); //保存进入新增编辑模态框的入口类型
  const [cliResRows, setCliResRows] = useState<any>(); //保存进入新增编辑模态框 的 点击行数据
  const intoTypeCal = useCallback(
    (resObj: any, intoType: string) => {
      setCliResRows(resObj);
      setIntoModalType(intoType);
    },
    [intoModalType, cliResRows],
  );

  // 表格操作方法
  const onPosOptClick: positionAPI.IOnPosOptClick = {
    onPosOption: (record, cliTye) => {
      onOpenUpdate(record, cliTye);
    },
    onPosView: (record) => {
      onDetail(record);
    },
    onChangeIsOpen: (checked, record) => {
      if (checked) {
        if (record?.pIsOpen == 1) {
          checkFalseIsOpen?.run(checked, record);
        } else if (record?.pIsOpen == 0) {
          onConfirmModal(record);
        } else {
          if (deptCheckRows?.isOpen == 1) {
            checkFalseIsOpen?.run(checked, record);
          } else {
            onConfirmModal(record);
          }
        }
      } else {
        onConfirmModal(record);
      }
    },
  };

  // 禁用组织机构
  const chanageCloseDept = (check: boolean, resObj: any) => {
    checkFalseIsOpen?.run(check, resObj);
  };

  // 调用修改状态的按钮
  const checkFalseIsOpen = useRequest(
    (openState: boolean, recObj: any) => {
      let params = {
        modifyerID: getUserID(),
        modifyPositionID: getPosIDs(),
        modifyDepartmentID: getUserDepID(),
        modifyCompanyID: getCompanyID(),
        versionNum: recObj?.versionNum,
        id: recObj?.id,
        isOpen: openState ? 1 : 0,
      };
      return rouleDutySubjectRequest(params, 'isOpen');
    },
    {
      manual: true,
      onSuccess: (res: any) => {
        if (res && res?.msgFlag) {
          message?.success(res?.msg);
          onTableReload();
        } else {
          message?.error(res?.msg);
        }
      },
    },
  );

  // 表格行操作
  const [showColumns, setShowColumns] = useState(getPosColumns(permissions, onPosOptClick));

  // 修改显示列
  const changeColumns = React.useCallback(
    (columns: any) => {
      setShowColumns(columns);
    },
    [showColumns],
  );

  return (
    <PositionContext.Provider
      value={{
        // viewId: viewId,
        curRes: permissions,
        selectedKeys: selectedKeys,
      }}
    >
      <div
        style={{
          position: 'relative',
          width: '100%',
          height: '100%',
          overflow: 'hidden',
        }}
      >
        <Row gutter={[8, 0]} className={cls(prefix)}>
          <Col span={6}>
            <OrganizationTree
              treeData={orgTreeData}
              loading={treeLoading}
              selectedKeys={selectedKeys}
              onTreeSelectChange={onTreeSelectChange}
              getTreeData={getTreeData}
              setDeptTreeNode={setDeptTreeNode}
            />
          </Col>
          <Col span={18}>
            <PositionTable
              loading={tableLoading}
              dataSource={dataSource}
              reload={onTableReload}
              onOpenUpdate={onOpenUpdate}
              columns={showColumns}
              deptCheckRows={deptCheckRows}
              changeColumns={changeColumns}
            />
          </Col>
        </Row>
        {/* 弹框逻辑处理 */}
        {showUpdateDrawer && (
          <UpdatePosModal
            onClose={onCloseUpdate}
            visible={showUpdateDrawer}
            dataSource={dataSource}
            treeData={orgTreeData}
            intoModalType={intoModalType}
            cliResRows={cliResRows}
            onTableReload={onTableReload}
            deptCheckRows={deptCheckRows}
          />
        )}

        {/* 禁用提示modal  */}
        {openConfirm && (
          <ConfirmModal
            visible={openConfirm}
            onClose={closeConfirmModal}
            onReload={onTableReload}
            chanageDeptState={chanageCloseDept}
            tableRowObj={tableRowObj}
            leftRowCheck={deptCheckRows}
          />
        )}

        <DetailInfoPosDrawer visible={isShowDetail} resObj={resObj} onCloseDra={closeDetail} />
      </div>
    </PositionContext.Provider>
  );
};

export default connect(({ baseLogin, navTab }: Record<string, any>) => ({
  permissions: baseLogin?.permissions,
  navTab,
}))(Index);
